<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .mouse {
        width: 100px;
        height: 100px;
        background: gray;
        position: fixed;
      }
    </style>
  </head>
  <body>
    <div class="mouse" id="m1"></div>
    <div class="mouse" id="m2"></div>
    <script>
      // 1. 选中要移动的对象
      const mouse = document.getElementById("m1");
      // 2. 监听键盘方向键
      window.onkeydown = function (e) {
        const { left, top } = mouse.getBoundingClientRect();
        if (e.key === "ArrowUp") {
          mouse.style.top = top - 20 + "px";
        }
        if (e.key === "ArrowDown") {
          mouse.style.top = top + 20 + "px";
        }
        if (e.key === "ArrowLeft") {
          mouse.style.left = left - 20 + "px";
        }
        if (e.key === "ArrowRight") {
          mouse.style.left = left + 20 + "px";
        }
      };
    </script>
  </body>
</html>
